﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CSF.Customers.Data;
using CSF.Utility.Mvc;
using CSF.Service.Accounts.Client;
using System.ServiceModel;

namespace CSF.WebApp.Accounts.Controllers
{
    public class CustomerController : SecureController
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ApplicationSvcClient svc = new ApplicationSvcClient();
            var application = svc.GetOneById(_userSession.ApplicationId);
            ViewBag.AppName = application.Name1;
            ViewBag.AppLogo = application.Logo;

            base.OnActionExecuting(filterContext);
        }

        //
        // GET: /Customer/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult MyDetail()
        {
            Customer customer = null;
            CustomerSvcClient svc = new CustomerSvcClient();
            var list = svc.GetByUser(_userSession.UserId);
            if (list != null)
            {
                customer = list.FirstOrDefault();
            }
            MyDetailViewData();
            return View(customer);
        }

        [Authorize]
        [HttpPost]
        public ActionResult MyDetail(Customer customer, string toUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    CustomerSvcClient svc = new CustomerSvcClient();
                    svc.UpdateBySelf(customer, User.Identity.Name);

                    if (!string.IsNullOrEmpty(toUrl))
                        return Redirect(toUrl);
                    else
                        return this.GoBack(2);
                }
                catch (FaultException ex)
                {
                    ModelState.AddModelError("", ex.Reason.ToString());
                }
            }
            MyDetailViewData();
            return View(customer);
        }

        [NonAction]
        private void MyDetailViewData()
        {
            CountrySvcClient countrySvc = new CountrySvcClient();
            var qcountry = from p in countrySvc.GetEnable()
                           orderby p.Name1
                           select new SelectListItem { Value = p.Code, Text = p.Name1 };
            ViewBag.CountryList = qcountry.AsEnumerable();
        }
    }
}
